<?php

namespace api\controllers;

use api\lib\GoodHelper;
use api\lib\OrderHelper;
use common\config\AppConf;
use common\libs\Constants;
use common\libs\Logger;
use Yii;
use yii\db\Expression;

class OrderController extends BaseController
{
    public $modelClass = "api\models\Order";
    public $searchModelClass = 'api\models\search\OrderSearch';
    protected $_redis;
    protected $_map;

    public function init()
    {
        parent::init();

        //使用redis缓存
        $this->_redis = Yii::$app->cache->redis;
        //初始化缓存所有商品信息
        $goodsData = GoodHelper::goodsList();
        foreach ($goodsData as $k => $v) {
            if (!$this->_redis->exists(Yii::$app->cache->keyPrefix . Constants::REDIS_PRODUCT_STOCK_PREFIX . $v['id']) && $v['stock'] > 0) {
                $this->_redis->set(Yii::$app->cache->keyPrefix . Constants::REDIS_PRODUCT_STOCK_PREFIX . $v['id'], $v['stock']);
            }
        }
    }

    /**
     * 去掉用户登录验证
     * @return array
     */
    public function behaviors()
    {
        $behavior = parent::behaviors();
        unset($behavior['authenticatior']);
        return $behavior;
    }


    /**
     * @return void
     */
    public function actionAdd()
    {

    }


    /**
     * User: wangxiaoxiao
     * Description: 下单接口
     * Example: http://api.seckill.com/order/seckill?goods_id=1
     */
    public function actionSeckill()
    {
        //获取数据
        $goodsId = Yii::$app->request->get('goods_id');
        
        //商品库存-1
        $stock = $this->_redis->decr(Yii::$app->cache->keyPrefix . Constants::REDIS_PRODUCT_STOCK_PREFIX . $goodsId);
        if ($stock < 0) {
            $this->_redis->incr(Yii::$app->cache->keyPrefix . Constants::REDIS_PRODUCT_STOCK_PREFIX . $goodsId);
            return $this->renderError('商品库存已售空', AppConf::APP_NO_DB);
        }

        //创建秒杀订单
        try {
            $re = OrderHelper::addOrder($userId = 1, $goodsId);
            Logger::info($re, '创建订单返回信息');
            return $this->renderError($re['no'], $re['msg']);
        } catch (\Exception $e) {
            $this->_redis->incr(Yii::$app->cache->keyPrefix . Constants::REDIS_PRODUCT_STOCK_PREFIX . $goodsId);
            Logger::error($e->getMessage(), '创建订单失败');
            return $this->renderError($e->getMessage(), AppConf::APP_NO_DB);
        }

    }
}
